package com.maochang.config.etc;

import com.maochang.pojo.PsUser;
import com.maochang.service.MenuService;
import com.maochang.service.PsUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class BbReam extends AuthorizingRealm {

    @Resource
    public PsUserService psUserServiceImpl;

    @Resource
    public MenuService MenuServiceImpl;




    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //第一步  认证已经传好对象了
        PsUser user=(PsUser) principalCollection.getPrimaryPrincipal();
        //System.out.println(user.getRoleId()+"adfasdfasdfasdfasdfa");
        List<String> permCodeList= MenuServiceImpl.seAchPermCode(user.getRoleId());
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permCodeList);
        return authorizationInfo;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //登录用户名
        String userCode= (String) token.getPrincipal();//拿到我们的用户名字 唯一标识符
        //通过登录用户名 判断有没有这个用户
        PsUser loginUser= psUserServiceImpl.searchByUserCode2(userCode);
        if(loginUser==null)return null;
        //信息返回

        SimpleAuthenticationInfo  simp=new SimpleAuthenticationInfo(loginUser,loginUser.getUserPassword(),ByteSource.Util.bytes(loginUser.getSalt()),super.getName());

        return simp;
    }
}
